from flask import Blueprint, jsonify, request
from utils.logger import get_logger
from utils.exceptions import (
    ValidationError, 
    AuthenticationError, 
    AuthorizationError, 
    ResourceNotFoundError, 
    DatabaseError, 
    ExternalServiceError
)

# 创建模块专用的日志器
logger = get_logger("api.error_demo")

# 创建蓝图
error_demo_bp = Blueprint('error_demo', __name__, url_prefix='/api/error-demo')

@error_demo_bp.route('/')
def index():
    logger.info("访问错误演示API首页")
    return jsonify({"message": "错误处理演示API", "endpoints": [
        "/validation",
        "/auth",
        "/permission",
        "/not-found",
        "/database",
        "/external-service",
        "/uncaught"
    ]})

@error_demo_bp.route('/validation')
def validation_error():
    """演示验证错误"""
    logger.info("演示验证错误")
    # 模拟参数验证失败
    param = request.args.get('id')
    if not param or not param.isdigit():
        details = {"id": "必须提供有效的数字ID"}
        raise ValidationError("参数验证失败", details=details)
    return jsonify({"status": "success", "message": "验证通过"})

@error_demo_bp.route('/auth')
def auth_error():
    """演示认证错误"""
    logger.info("演示认证错误")
    # 模拟认证失败
    token = request.headers.get('Authorization')
    if not token:
        raise AuthenticationError("缺少认证令牌")
    return jsonify({"status": "success", "message": "认证成功"})

@error_demo_bp.route('/permission')
def permission_error():
    """演示权限错误"""
    logger.info("演示权限错误")
    # 模拟权限不足
    user_role = request.args.get('role', 'user')
    if user_role != 'admin':
        raise AuthorizationError(f"需要管理员权限，当前角色: {user_role}")
    return jsonify({"status": "success", "message": "有权限访问"})

@error_demo_bp.route('/not-found')
def not_found_error():
    """演示资源不存在错误"""
    logger.info("演示资源不存在错误")
    # 模拟资源不存在
    resource_id = request.args.get('id', '999')
    # 假设ID为999的资源不存在
    if resource_id == '999':
        raise ResourceNotFoundError("用户", resource_id)
    return jsonify({"status": "success", "message": "资源存在"})

@error_demo_bp.route('/database')
def database_error():
    """演示数据库错误"""
    logger.info("演示数据库错误")
    # 模拟数据库错误
    if not request.args.get('fix'):
        # 创建一个异常对象用于记录详细错误信息
        db_exception = Exception("数据库连接超时")
        raise DatabaseError("数据库查询失败", exc_info=db_exception)
    return jsonify({"status": "success", "message": "数据库操作成功"})

@error_demo_bp.route('/external-service')
def external_service_error():
    """演示外部服务错误"""
    logger.info("演示外部服务错误")
    # 模拟外部服务错误
    service = request.args.get('service', 'payment')
    if service == 'payment':
        # 创建一个异常对象用于记录详细错误信息
        service_exception = Exception("支付网关响应超时")
        raise ExternalServiceError("支付服务", "处理支付请求失败", exc_info=service_exception)
    return jsonify({"status": "success", "message": "外部服务调用成功"})

@error_demo_bp.route('/uncaught')
def uncaught_error():
    """演示未捕获的异常"""
    logger.info("演示未捕获的异常")
    # 故意引发一个未捕获的异常
    undefined_variable = some_undefined_variable  # 这会引发NameError
    return jsonify({"status": "success", "message": "这段代码永远不会执行"})